import json

from flask import Blueprint, render_template, current_app, request, session, redirect, g, jsonify
from flask_jwt_extended import jwt_required, get_current_user
from extensions import db
from orms import *

index_bp = Blueprint('index', __name__)


@index_bp.route('/')
@jwt_required(optional=True)
def hello_world():
    # return render_template('index.html')
    # 显示登陆状态 jinjia2渲染
    current_user: UserORM = get_current_user()
    # 首页文章数据
    page = request.args.get('page', type=int, default=1)
    per_page = request.args.get('limit', type=int, default=10)

    q = db.select(ArticleORM)
    # 筛选查询
    cid = request.args.get('cid', type=int, default=1)
    if cid != 1:
        q = q.where(ArticleORM.category_id == cid)
        q = q.order_by(ArticleORM.id)
    q = q.order_by(ArticleORM.create_at.desc())

    pag = db.paginate(q, page=page, per_page=per_page, error_out=False)

    article_list = pag.items

    cate_list = CategoryORM.query.all()
    # 热门文章
    side_q = db.select(ArticleORM).order_by(ArticleORM.clicks.desc()).limit(10)
    click_article = db.session.execute(side_q).scalars()
    # print(click_article)
    return render_template(
        'index.html',
        current_user=current_user,
        article_list=article_list,
        cate_list=cate_list,
        pag=pag,
        click_article=click_article,
    )


@index_bp.route('/load_more', methods=['POST'])
def load_more():
    last_article_id = request.form.get('lastArticleId')
    # Simulate getting new articles from the database
    new_articles = get_new_articles(last_article_id)
    return jsonify(new_articles=new_articles, pages=5)


@index_bp.route('/append_data', methods=['POST'])
def append_data():
    last_article_id = request.form.get('lastArticleId')
    # Simulate getting new articles from the database
    new_articles = get_new_articles(last_article_id)
    # Append new articles to the existing ones
    existing_articles = request.form.get('existingArticles')
    print('[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[')
    print(existing_articles)
    if existing_articles is None:
        existing_articles = []
    else:
        existing_articles = json.loads(existing_articles)
    existing_articles.extend(new_articles)
    return jsonify(new_articles=existing_articles, pages=5)


def get_new_articles(last_article_id):
    # Query the database for articles with an id greater than last_article_id
    new_articles = ArticleORM.query.filter(ArticleORM.id > last_article_id).limit(5).all()
    if not new_articles:
        return ["文章已经到底了"]
    return [article.to_dict() for article in new_articles]
